package com.whjfxx.terminal.commons;

import com.whjfxx.terminal.enums.Comment;
import com.whjfxx.terminal.enums.IEnum;
import com.whjfxx.terminal.utils.BeanUtils;
import com.whjfxx.terminal.utils.EnumUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * Created by b.c on 2022/5/19 11:06
 */
public class EnumSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeObject(value);
        if (null == null) {
            return;
        }
        String currentName = gen.getOutputContext().getCurrentName();
        Comment annotation = BeanUtils.getFieldAnnotation(gen.getCurrentValue().getClass(), currentName, Comment.class);
        if (null == annotation) {
            return;
        }
        if (annotation.clazz().isEnum()) {
            Class<?>[] classes = annotation.clazz().getInterfaces();
            for (Class<?> clazz : classes) {
                if (clazz == IEnum.class) {
                    String fieldName = currentName + "Desc";
                    if (annotation.fields().length > 0) {
                        fieldName = annotation.fields()[0];
                    }
                    if (BeanUtils.isExistField(gen.getCurrentValue().getClass(), fieldName)) {
                    } else {

                        String fieldNameValue = EnumUtils
                                .getDescriptionByValue(value.toString(), (Class<? extends IEnum>)annotation.clazz());
                        if (StringUtils.isBlank(fieldNameValue) && StringUtils.isNotBlank(annotation.def())) {
                            fieldNameValue = annotation.def();
                        }
                        gen.writeStringField(fieldName, fieldNameValue);
                    }

                }
            }
        }
    }

}
